<template>
  <div class="blog-comment-container">
    <MessageArea
      title="评论列表"
      :total="data.total"
      :list="data.rows"
      @submit="handleSubmit"
      :isListLoading="this.isLoading"
      :text="text"
    ></MessageArea>
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import { getComments } from "@/api/blog";
import { postComment } from "@/api/blog";
import fetchData from "@/mixins/fetchData";
export default {
  mixins: [fetchData({})],
  data() {
    return {
      limit: 10,
      page: 1,
      text: "",
    };
  },
  components: {
    MessageArea,
  },
  created() {
    this.$eventBus.$on("mainScroll", this.fetchNextPage);
  },
  destroyed() {
    this.$eventBus.$off("mainScroll", this.fetchNextPage);
  },
  computed: {
    hasMore() {
      return this.data.rows.length >= this.data.total;
    },
  },
  methods: {
    async fetchMore() {
      if (this.data.rows.length === 0) {
        this.text = "-------博主很菜，请大佬们给点建议------";
        return;
      }
      if (this.hasMore) {
        this.text = "------我也是有底线的------";
        return;
      }
      this.isLoading = true;
      this.page++;
      const resp = await this.fetchData();
      this.data.rows = this.data.rows.concat(resp.rows);
      this.isLoading = false;
    },
    async fetchData() {
      return await getComments(this.$route.params.id, this.page, this.limit);
    },
    async handleSubmit(formData, callback) {
      const resp = await postComment({
        blogId: this.$route.params.id,
        ...formData,
      });
      if (!resp) {
        callback("您的操作过于频繁，请稍后再试", "info");
      } else {
        //   this.data.rows.unshift(resp);
        this.data.total++;
        this.data = await getComments(
          this.$route.params.id,
          this.page,
          this.data.total
        );
        callback("评论成功");
      }
    },
    fetchNextPage(dom) {
      if (this.isLoading || !dom) {
        return;
      }
      let range = 100;
      let dec = Math.abs(dom.scrollTop + dom.clientHeight - dom.scrollHeight);
      if (dec <= range) {
        this.fetchMore();
      }
    },
  },
};
</script>

<style lang="less" scoped>
.blog-comment-container {
  width: 100%;
  padding-top: 20px;
}
</style>